 package com.handong.handserialprogram.module.createmission.recordtask;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.model.PersonModel;
import com.handong.handserialprogram.model.entities.PersonEntity;
import com.handong.handserialprogram.model.entities.UploadTaskEntity;
import com.handong.handserialprogram.module.base.SimpleFragment;
import com.handong.handserialprogram.utils.AsyncHttpUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.SPUtil;
import com.handong.handserialprogram.utils.ViewUtil;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;

import java.util.ArrayList;

/**
 * CarFragment:选择车辆。
 */
public class CarFragment extends SimpleFragment {

    private static final String TAG = CarFragment.class.getSimpleName();
    public static final String CHOOSE_CAR = "choose_car";
    private static final String IS_CAR = "isCar";
    private String mChooseCar, mCarIdName;

    private RecyclerView mCarRecyclerView;
    private LinearLayout mLoadingLayout;
    private CarAdapter mCarAdapter;


    private int mFragmentType = 0;
    public static final int TYPE_CAR = 1;
    public static final int TYPE_LINE = 2;
    private boolean isCar;
    private String mTitle;
    public CarFragment() {
    }

    public static CarFragment newInstance(String chooseCar,boolean isCar) {
        CarFragment fragment = new CarFragment();
        Bundle args = new Bundle();
        args.putString(CHOOSE_CAR, chooseCar);
        args.putBoolean(IS_CAR, isCar);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mChooseCar = getArguments().getString(CHOOSE_CAR);
            isCar = getArguments().getBoolean(IS_CAR);
            if (isCar) {
                mFragmentType = TYPE_CAR;
            } else {
                mFragmentType = TYPE_LINE;
            }
        }
    }

    @Override
    protected void initViewByID(View contentView) {
        mTitle = getString(mFragmentType == TYPE_CAR ? R.string.title_choose_car_string
                : R.string.title_choose_line_string);
        initHeaderLayout(mTitle, getString(R.string.dialog_positive_text));
        mLoadingLayout = (LinearLayout) contentView.findViewById(R.id.progressBarLayout);
        mCarRecyclerView = (RecyclerView) contentView.findViewById(R.id.taskCarRecyclerView);
        if (mFragmentType == TYPE_CAR) {
            requestCarList();
        } else {
            requestLineList();
        }
    }

    @Override
    protected int getContentViewID() {
        return R.layout.fragment_car;
    }

    @Override
    public void onClick(View v) {
        if (dispatchDoubleClick()){
            return;
        }
        switch (v.getId()) {
            case R.id.headerOptionLayout:
                mActivity.saveTaskInfo(mChooseCar, mCarIdName,isCar);
                removeFragment();
                break;
            default:
                super.onClick(v);
        }
    }

    private void requestCarList() {
        RequestParams params = new RequestParams();
        params.put("visit", "GetCar");
        params.put("sys_companycode", SPUtil.getStringValue(SPUtil.LOGIN_CODE));

        AsyncHttpUtil.postSpecifiedRequest(getContext(), params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                JLog.d(TAG, throwable.toString());
                getCarListError("");
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                JLog.d(TAG, s);
                if (!TextUtils.isEmpty(s) && s.length() < 15) {
                    return;
                }
                Gson gson = new Gson();
                PersonModel model = gson.fromJson(s, PersonModel.class);
                if (model.isSuccess()) {
                    getCarListSuccess(model.getList());
                } else {
                    getCarListError(model.getReason());
                }
            }
        });
    }
    //获取路线
    private void requestLineList() {
        RequestParams params = new RequestParams();
        params.put("visit", "GetRoute");
        params.put("sys_companycode", SPUtil.getStringValue(SPUtil.LOGIN_CODE));
        AsyncHttpUtil.postRequest(params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                JLog.d(TAG, throwable.toString());
                getLineListError("");
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                JLog.d(TAG, s);
                if (TextUtils.isEmpty(s) || s.length() < 15) {
                    return;
                }
                Gson gson = new Gson();
                PersonModel model = gson.fromJson(s, PersonModel.class);
                if (model.isSuccess()) {
                    getCarListSuccess(model.getList());
                } else {
                    getLineListError(model.getReason());
                }
            }
        });

    }

    private void getCarListError(String reason) {
        View itemView = mLoadingLayout.getChildAt(0);
        if (itemView instanceof ImageView) {
            dismissLoadingDialog();
            return;
        }
        FrameLayout parent = (FrameLayout) mLoadingLayout.getParent();
        parent.removeView(mLoadingLayout);
        mLoadingLayout = super.showTipLayout(R.drawable.load_tip_error, R.string.tip_load_car_error, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoadDialog(getString(R.string.dialog_content_loading_car));
                requestCarList();
            }
        });
        parent.addView(mLoadingLayout, 0);
    }
    //获取路线失败
    private void getLineListError(String reason) {
        View itemView = mLoadingLayout.getChildAt(0);
        if (itemView instanceof ImageView) {
            dismissLoadingDialog();
            return;
        }
        FrameLayout parent = (FrameLayout) mLoadingLayout.getParent();
        parent.removeView(mLoadingLayout);
        mLoadingLayout = super.showTipLayout(R.drawable.load_tip_error, R.string.tip_load_line_error, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoadDialog(getString(R.string.dialog_content_loading_line));
                requestLineList();
            }
        });
        parent.addView(mLoadingLayout, 0);
    }
    private void getCarListSuccess(ArrayList<PersonEntity> list) {
        if (list.isEmpty()) {
            getCarListEmpty();
            return;
        }
        View view = mLoadingLayout.getChildAt(0);
        if (view instanceof ImageView) {
            dismissLoadingDialog();
        }
        if (mLoadingLayout != null) {
            FrameLayout parent = (FrameLayout) mLoadingLayout.getParent();
            parent.removeView(mLoadingLayout);
            mLoadingLayout = null;
        }
        UploadTaskEntity mTaskEntity = new UploadTaskEntity();
        if (!TextUtils.isEmpty(mChooseCar)) {//标记选中车辆。
            for (PersonEntity entity : list) {
                if (mChooseCar.equals(entity.getId())) {
                    entity.setChecked(true);
                    mCarIdName = entity.getName();
                    mChooseCar = entity.getId();
                    break;
                }
            }
        }
        mCarAdapter = new CarAdapter(list, this,isCar);
        mCarRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mCarRecyclerView.setAdapter(mCarAdapter);
        mCarRecyclerView.setVisibility(View.VISIBLE);
    }
    private void getCarListEmpty() {
        FrameLayout parent = (FrameLayout) mLoadingLayout.getParent();
        parent.removeView(mLoadingLayout);
        mLoadingLayout = null;
        LinearLayout layout = super.showTipLayout(R.drawable.load_tip_empty, R.string.tip_no_car, null);
        parent.addView(layout, 0);
    }
    private void getLineListEmpty() {
        FrameLayout parent = (FrameLayout) mLoadingLayout.getParent();
        parent.removeView(mLoadingLayout);
        mLoadingLayout = null;
        LinearLayout layout = super.showTipLayout(R.drawable.load_tip_empty, R.string.tip_no_line, null);
        parent.addView(layout, 0);
    }
    public void setChooseCar(String id, String name) {
        mChooseCar = id;
        mCarIdName = name;
    }

    @Override
    protected boolean onBackClicked() {
        if (mCarAdapter != null && !TextUtils.isEmpty(mChooseCar)) {
            showExitWarningDialog();
            return true;
        }
        return false;
    }

    @SuppressLint("StringFormatInvalid")
    private void showExitWarningDialog() {
        MaterialDialog dialog = new MaterialDialog.Builder(getContext())
                .title(R.string.dialog_title_careful)
                .content(getResources().getString(R.string.dialog_content_give_up_person, isCar?"车辆":"路线"))
                        .positiveColorRes(R.color.back_ground_green)
                        .positiveText(R.string.dialog_positive_exit)
                        .negativeColorRes(R.color.bg_gray)
                        .negativeText(R.string.dialog_negative_text)
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                mChooseCar = "";
                                mActivity.saveTaskInfo("", "",isCar);
                                removeFragment();
                            }
                        })
                        .build();
        ViewUtil.removeHomeKeyListener(dialog);
    }

    @Override
    public void onDestroyView() {
        if (mCarAdapter != null) {
            mCarAdapter.onDestroy();
            mCarAdapter = null;
        }
        AsyncHttpUtil.cancelSpecifiedRequest(getContext());
        super.onDestroyView();
    }
}
